//
//  RecommendController.m
//  MyTrip
//
//  Created by zhang on 15/8/22.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "RecommendController.h"
#import "HeaderView.h"
#import "AsyncGETConnection.h"
#import "TitleCell.h"
#import "RobCell.h"
#import "FoundAllCell.h"
#import "TravelCell.h"
#import "RoundView.h"
#import "HearButtonView.h"
#import "SlideController.h"
#import "LookController.h"
#import "RobController.h"
#import "MJRefresh.h"
#import "DKNightVersion.h"
#import "MBProgressHUD.h"
#define Width self.view.frame.size.width
#define Height self.view.frame.size.height


@interface RecommendController ()<UITableViewDataSource, UITableViewDelegate, HearButtonViewDelegate, HeaderViewDelegate, RobCellDelegate>
@property (retain, nonatomic) UITableView *table;
@property (retain, nonatomic) NSMutableArray *slideArray;
@property (retain, nonatomic) HeaderView *header;
@property (retain, nonatomic) NSMutableArray *robArray;
@property (retain, nonatomic) NSMutableArray *discountArray;
@property (retain, nonatomic) NSMutableArray *travelArray;
@property (retain, nonatomic) MBProgressHUD *hud;
@property (retain, nonatomic) UIView *myView;

@end

@implementation RecommendController

- (void)dealloc
{
    [_travelArray release];
    [_robArray release];
    [_header release];
    [_table release];
    [_slideArray release];
    [_discountArray release];
    [super dealloc];
}

- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.slideArray = [NSMutableArray array];
        self.robArray = [NSMutableArray array];
        self.discountArray = [NSMutableArray array];
        self.travelArray = [NSMutableArray array];
    }
    return self;
}
- (void)getMessage{
    self.hud = [[MBProgressHUD alloc] init];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"玩命加载中.....";
    //    在网络请求之后
    
    __block MBProgressHUD *hud = _hud;
    [self performSelector:@selector(remover:) withObject:nil afterDelay:5];
    [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=352203060549304&track_app_version=6.5.5&track_app_channel=qq&track_device_info=hllte&track_os=Android4.3&app_installtime=1440071883272&lat=38.88366&lon=121.543944&channel=qq" parameters:nil messageBlock:^(NSData *data) {
        hud.hidden = YES;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        NSArray *slide = [dataDic objectForKey:@"slide"];
        NSArray *rob = [dataDic objectForKey:@"discount_subject"];
        NSArray *discount = [dataDic objectForKey:@"discount"];
        [_header.figureArray addObjectsFromArray:slide];
        [_robArray addObjectsFromArray:rob];
        [_discountArray addObjectsFromArray:discount];
        [_header createPage];
        [_header.figureCollection reloadData];
        [_table reloadData];
    }];
    
    [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=352203060549304&track_app_version=6.5.5&track_app_channel=qq&track_device_info=hllte&track_os=Android4.3&app_installtime=1440071883272&lat=38.883596&lon=121.544153&type=index&page=1&count=10" parameters:nil messageBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = [dic objectForKey:@"data"];
        [_travelArray addObjectsFromArray:dataArray];
        [_table reloadData];
    }];
}

- (void)remover:(MBProgressHUD *)hud{
    hud = _hud;
    if (hud.hidden == NO) {
        hud.hidden = YES;
    }
}

#pragma mark - <headerviewdelegate>

- (void)clickedIndexPath:(NSIndexPath *)indexPath WithURL:(NSString *)URL{
    SlideController *slide = [[SlideController alloc] init];
    slide.url = URL;
    [self.navigationController pushViewController:slide animated:YES];
    [slide release];
}


#pragma mark - <headerButtondelegate>

- (void)sendRoundView:(RoundView *)round{
    if (round.tag == 1) {
        LookController *look = [[LookController alloc] init];
        [self.navigationController pushViewController:look animated:YES];
        [look release];

    }else if (round.tag == 2){
        RobController *rob = [[RobController alloc] init];
        [self.navigationController pushViewController:rob animated:YES];
        [rob release];
    }else if (round.tag == 3){
        SlideController *slide = [[SlideController alloc] init];
        slide.url = @"http://hotel.qunar.com";
        [self.navigationController pushViewController:slide animated:YES];
        [slide release];
        
    }else if (round.tag == 4){
        SlideController *slide = [[SlideController alloc] init];
        slide.url = @"http://piao.qunar.com";
        [self.navigationController pushViewController:slide animated:YES];
        [slide release];
    }
}





#pragma mark - <创建tableview>
- (void)createTable{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Width, Height) style:UITableViewStyleGrouped];
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerClass:[TitleCell class] forCellReuseIdentifier:@"title"];
    [_table registerClass:[RobCell class] forCellReuseIdentifier:@"rob"];
    [_table registerClass:[FoundAllCell class] forCellReuseIdentifier:@"foundAll"];
    [_table registerClass:[TravelCell class] forCellReuseIdentifier:@"travel"];
    [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_table];
    self.header = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, Width, 325 * OffHeight)];
    _header.header.delegate = self;
    _header.delegate = self;
    _table.tableHeaderView = _header;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }
    if (section == 1) {
        return _travelArray.count + 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 190 * OffHeight;
        }else if (indexPath.row == 1){
            
            return 370 * OffHeight;
        }else if (indexPath.row == 2){
            return 50 * OffHeight;
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 40 * OffHeight;
        }else{
            return 100 * OffHeight;
        }
    }
    else{
        return 30 * OffHeight;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            TitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"title"];
            if (_robArray.count != 0) {
                NSDictionary *dic = [_robArray objectAtIndex:0];
                [cell setValueWithDic:dic];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
        if (indexPath.row == 1) {
            RobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rob"];
            cell.delegate = self;
            if (_discountArray.count != 0) {
                cell.robCollectionArray = _discountArray;
            }
            [cell.robCollection reloadData];
            return cell;
        }
        if (indexPath.row == 2) {
            FoundAllCell *cell = [tableView dequeueReusableCellWithIdentifier:@"foundAll"];
            [cell setValueForCell];
            return cell;
        }
    }else if (indexPath.section == 1 || _travelArray.count != 0){
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            cell.textLabel.text = @"看热门游记";
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.alpha = 0.5;
            return cell;
        }else{
            TravelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travel"];
            NSDictionary *dic = [_travelArray objectAtIndex:indexPath.row - 1];
            [cell setValueWithDic:dic];
            return cell;
        }
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
           NSDictionary *dic = [_robArray objectAtIndex:0];
            NSString *url = [dic objectForKey:@"url"];
            SlideController *slide = [[SlideController alloc] init];
            slide.url = url;
            [self.navigationController pushViewController:slide animated:YES];
            [slide release];
        }
        else if (indexPath.row == 2){
            RobController *rob = [[RobController alloc] init];
            [self.navigationController pushViewController:rob animated:YES];
            [rob release];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row > 0) {
            NSDictionary *dic = [_travelArray objectAtIndex:indexPath.row - 1];
            NSString *url = [dic objectForKey:@"view_url"];
            SlideController *slider = [[SlideController alloc] init];
            slider.url = url;
            [self.navigationController pushViewController:slider animated:YES];
            [slider release];

        }
    }
}

- (void)clickIndex:(NSIndexPath *)indexPath WithidNum:(NSNumber *)idNum{
    NSString *url = [NSString stringWithFormat:@"http://z.qyer.com/deal/%@/", idNum];
    SlideController *slide = [[SlideController alloc] init];
    slide.url = url;
    [self.navigationController pushViewController:slide animated:YES];
    [slide release];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0f green:160 / 255.0f blue:175 / 255.0f alpha:1];
    UIImage * reSel = [UIImage imageNamed:@"tuijians"];
    reSel = [reSel imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarController.tabBar.selectedItem.selectedImage = reSel;
    self.navigationItem.title = @"推荐";
    [self createTable];
     [self getMessage];
    
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    self.navigationItem.leftBarButtonItem.nightTintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.nightTintColor = [UIColor whiteColor];
    
    [_table addFooterWithCallback:^{
        _hud.hidden = NO;
        static int currentPage = 2;
        [AsyncGETConnection asyncGETConnectionWithURLStr:[NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=352203060549304&track_app_version=6.5.5&track_app_channel=qq&track_device_info=hllte&track_os=Android4.3&app_installtime=1440071883272&lat=38.883596&lon=121.544153&type=index&page=%d&count=10", currentPage] parameters:nil messageBlock:^(NSData *data) {
            _hud.hidden = YES;
            currentPage++;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *dataArray = [dic objectForKey:@"data"];
            [_travelArray addObjectsFromArray:dataArray];
            [_table reloadData];
            [_table footerEndRefreshing];
    }];
    
    }];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
